
pipeline {
    agent { label "label-master" }

    options {
        timestamps()                    // 在日志中打印时间
        timeout(time:1, unit:'HOURS')   // 流水线超时设置为1H
        // retry(2)                        // 失败重试2次
    }
    
    //最好在配置里创建一遍或者点一次build now，否则第一次运行没有Build with parameters
    parameters {
        choice (name: 'PublishServer', choices: ['prod8-recovery'], description: '切换站点的服务器')
        extendedChoice ( 
            name: 'ProjectNames', 
            defaultValue: '', 
            description: '发布的项目，可多选。注意：配置相关的文件需要自己手动修改', 
            multiSelectDelimiter: ';', 
            quoteValue: false, 
            saveJSONParameterToFile: false, 
            type: 'PT_MULTI_SELECT', 
            value:'trunklpg,SaaSAPPlpg,DccAdmin,NewWXShoplpg,09API_WebAPI,09API_WebAPI_LPG', 
            visibleItemCount: 7
        )
    }

    stages {
        stage("InitParamters") {
            steps {
                script {
                    wrap([$class: 'BuildUser']) {
                        buildName "${BUILD_NUMBER}-${env.BUILD_USER}-${PublishServer}-${ProjectNames}"
                    }
                    if (ProjectNames == "") {
                        println "The ProjectNames does not exists."
                        error "This pipeline stops here!"
                    }

                    json_file = "C:\\Jenkins\\resources\\input.lanyang.prod.json"
                    Boolean isExists = fileExists json_file
                    if (!isExists) {
                        println "The Input_Json File does not exists."
                        error "This pipeline stops here!"
                    }
                    prop = readJSON file : json_file

                    isCrossServer = true
                    println "isCrossServer: " + isCrossServer
                                        
                }
            }
        }
        
        stage('Switch') {
            agent { label "label-${PublishServer}" }

            steps {
                timeout(time:15, unit:'MINUTES') {
                    script {
                        for (project_name in ProjectNames.tokenize(';')) {
                            println "start switch project: " + project_name  
                            for (appPool in prop.envs[PublishServer][project_name]) {
                                appPoolFullName = appPool.appPoolFullName ? appPool.appPoolFullName : ""
                                appPoolPhysicalPath = appPool.appPoolPhysicalPath ? appPool.appPoolPhysicalPath : ""
                                changeIISAppPoolPath(appPoolFullName, appPoolPhysicalPath, isCrossServer)
                            
                                sleep(30)
                            }
                        }
                        
                    }
                }
            }
        }
    }

    post {
        success {
            wrap([$class: 'BuildUser']) {
                echo '恭喜您，构建成功！！！'
                mail subject: "CI报告: ${env.JOB_NAME} [${env.BUILD_NUMBER}] 执行成功",
                body: """
                    <style>
                    ul li { padding: 8px 0; }
                    ul li .title { min-width: 130px; display: inline-block; }
                    </style>
                    <div id="content">
                        <div id="sum2">
                            <h2><font color=#00CD00>Jenkins 运行成功</font></h2>
                            <ul>
                                <li><label class="title">Jenkins Job Name:</label> <a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a></li>
                                <li><label class="title">Jenkins Job URL:</label> <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                                <li><label class="title">Jenkins Log:</label> <a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                                <li><label class="title">发布环境:</label> ${params.PublishServer}</li>
                                <li><label class="title">发布项目:</label> <font color=#00CD00>${params.ProjectNames}</font></li>
                                <li><label class="title">发布人:</label> ${BUILD_USER}</li>
                            </ul>
                        </div>
                    </div>
                    """,
                charset: 'utf-8',
                from: '2167162@qq.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}, lufei@lanyang.com"
            }
        }
        failure {
            wrap([$class: 'BuildUser']) {
                echo '抱歉，构建失败！！！'
                mail subject: "CI报告: ${env.JOB_NAME} [${env.BUILD_NUMBER}] 执行失败",
                body: """
                    <style>
                    ul li { padding: 8px 0; }
                    ul li .title { min-width: 130px; display: inline-block; }
                    </style>
                    <div id="content">
                        <div id="sum2">
                            <h2><font color=#EE0000>Jenkins 运行失败</font></h2>
                            <ul>
                                <li><label class="title">Jenkins Job Name:</label> <a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a></li>
                                <li><label class="title">Jenkins Job URL:</label> <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                                <li><label class="title">Jenkins Log:</label> <a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                                <li><label class="title">发布环境:</label> ${params.PublishServer}</li>
                                <li><label class="title">发布项目:</label> <font color=#EE0000>${params.ProjectNames}</font></li>
                                <li><label class="title">发布人:</label> ${BUILD_USER}</li>
                            </ul>
                        </div>
                    </div>
                """,
                charset: 'utf-8',
                from: '2167162@qq.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}, lufei@lanyang.com"
            }
        }
    }
}

// %systemroot%\system32\inetsrv\appcmd set app "站点名字/应用程序名字" /["path='/'].physicalPath:"新的路径"
def changeIISAppPoolPath(appPoolFullName, appPoolPhysicalPath, isCrossServer) {
    println "start changeIISAppPoolPath function"
    println "appPoolFullName:" + appPoolFullName
    println "appPoolPhysicalPath:" + appPoolPhysicalPath

    retry(2) {
        bat """
            %1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
            
            set appPoolFullName="${appPoolFullName}"
            set appPoolPhysicalPath="${appPoolPhysicalPath}"
            
            IF %appPoolFullName% NEQ "" (
                echo "[Debug:info] app pool: %appPoolFullName%"
                C:\\Windows\\System32\\inetsrv\\appcmd.exe set app %appPoolFullName% /["path='/'].physicalPath:%appPoolPhysicalPath%
                IF %ERRORLEVEL% NEQ 0 GOTO ERROR
            )
            
            :OK
            ECHO command success
            EXIT 0

            :ERROR
            ECHO command failed
            EXIT 1
        """
    }
}
